package com.lagou.testmetadata;

import com.lagou.Utils.DruidUtils;
import org.junit.Test;

import java.sql.*;

import static com.lagou.Utils.DruidUtils.close;

public class TestMetaData {
    //1.获取数据库相关的元数据信息 使用DatabaseMetaData
    @Test
    public void testDataBaseMetaData() throws SQLException {

        //1.获取数据库连接对象
        Connection connection= DruidUtils.getConnection();

        //2.获取代表数据库的 元数据对象 DatabaseMetaData
        DatabaseMetaData metaData = connection.getMetaData();

        //3.获取数据库相关的元数据信息
        String url = metaData.getURL();
        System.out.println("数据库的URL为:"+url);

        String userName = metaData.getUserName();
        System.out.println("当前用户为:"+userName);

        String databaseProductName = metaData.getDatabaseProductName();
        System.out.println("数据库产品名:"+databaseProductName);

        String databaseProductVersion = metaData.getDatabaseProductVersion();
        System.out.println("数据库版本:"+databaseProductVersion);

        String driverName = metaData.getDriverName();
        System.out.println("驱动名称:"+driverName);

        //判断当前数据库是否只允许只读
        boolean readOnly = metaData.isReadOnly();
        System.out.println("当前数据库是否只允许只读:"+readOnly);
        //如果是true 就表示只读
        if(readOnly){
            System.out.println("当前数据库只允许读操作!");
        }else{
            System.out.println("不是只读数据库!");
        }

        //释放资源
        connection.close();
    }



    //获取结果集中的元数据信息
    @Test
    public void testResultSetMetaData() throws SQLException {

        //1.获取连接
        Connection connection=DruidUtils.getConnection();

        //2.获取预处理对象
        PreparedStatement preparedStatement=connection.prepareStatement("select * from employee");
        ResultSet resultSet=preparedStatement.executeQuery();

        //3.获取结果集元数据对象
        ResultSetMetaData metaData = preparedStatement.getMetaData();

        //3.1获取当前结果集 共有多少列
        int columnCount = metaData.getColumnCount();
        System.out.println("当前结果集中共有:"+columnCount+"列");

        //3.2获取结果集中 列的名称和类型

        for (int i = 1; i <columnCount ; i++) {
        String columnName = metaData.getColumnName(i);
        System.out.println("第"+i+"列的列名为:"+columnName);

        String columnTypeName = metaData.getColumnTypeName(i);
        System.out.println("第"+i+"列的类型为:"+columnTypeName);

        }

        //释放资源
        DruidUtils.close(connection,preparedStatement,resultSet);
    }
}
